package SortAlgorithm;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname RadixSort 基数排序
 * @Description TODO  将待排序数值统一长度， 补零，然后从最低位开始排序，一直到最高位排序完成
 * @Date 2021/11/15 9:17
 * @Created K024851
 */
public class RadixSort {
    public static void main(String[] args) {
//        int[] arr = new int[80000];
//        for (int i = 0; i < 80000; i++) {
//            arr[i] = (int) (Math.random() * 8000000);
//        }
        int[] arr = {53,3,542,748,14,214};
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println("排序前：" + format);
        int[] temp = new int[arr.length];
        radixSort(arr);
        Date date2 = new Date();
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format2 = simpleDateFormat2.format(date2);
        System.out.println("排序后：" + format2);

    }

    public static void radixSort(int[] arr) {
        //1、得到数组中最大的数
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i]>max){
                max = arr[i];
            }
        }

        //最大数的位置
        int maxL = (max+"").length();


        //为什么是10？ 1-9 为10
        int[][] bucket = new int[10][arr.length];
        int[] bucketElementCounts = new int[10];
        for (int i=0,n=1;i<maxL;i++,n *= 10){
            for (int j=0;j<arr.length;j++){
                int digitOfElement = arr[j]/n%10;
                bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
                bucketElementCounts[digitOfElement]++;
            }
            int index = 0;
            for (int k=0;k<bucketElementCounts.length;k++){
                if (bucketElementCounts[k] != 0){
                    for (int l=0;l<bucketElementCounts[k];l++){
                        arr[index++] = bucket[k][l];
                    }
                }
                //第i+1轮后，需要将每个   bucketElementCounts[k] = 0;
                bucketElementCounts[k] = 0;
            }
        }

    }

}
